package com.shj.em.biz.prod.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.shj.em.base.controller.BaseController;
import com.shj.em.base.support.ResMsg;
import com.shj.em.base.vo.PageVO;
import com.shj.em.biz.sell.entity.Order;
import com.shj.em.biz.sell.service.OrderService;
import com.shj.em.biz.prod.dto.OrderEffortDTO;
import com.shj.em.biz.prod.entity.Effort;
import com.shj.em.biz.prod.service.EffortService;
import com.shj.em.biz.hr.entity.Dept;
import com.shj.em.biz.hr.entity.Emp;
import com.shj.em.biz.sys.entity.RankAmount;
import com.shj.em.biz.hr.service.DeptService;
import com.shj.em.biz.hr.service.EmpService;
import com.shj.em.common.annotation.Log;
import com.shj.em.util.ShiroUtils;
import com.shj.em.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;


/**
 * <p>
 * 员工工作时间表 前端控制器
 * </p>
 *
 * @author Shen Huang Jian
 * @since 2018-07-16
 */
@Controller
@Slf4j
@RequestMapping("/prod/effort")
public class EffortController extends BaseController<Effort>{

    private String prefix = "prod/effort";

    @Autowired
    EffortService effortService;

    @Autowired
    DeptService deptService;

    @Autowired
    EmpService empService;

    @Autowired
    OrderService orderService;

    //二部工时录入 菜单
    @GetMapping("/gotoSearch")
    public String gotoSearch(){
        return prefix + "/search_order";
    }

    /**
     * 用于查找单个员工的工时信息
     * @return
     */
    @GetMapping("/gotoEmpSearch")
    public String gotoEmpSearch(Model model){
        Calendar cal = Calendar.getInstance();
        model.addAttribute("year", cal.get(Calendar.YEAR));
        model.addAttribute("month", cal.get(Calendar.MONTH) + 1);

        List<Dept> depts = deptService.findAllProdGroupTwoDepts();
        model.addAttribute("depts", depts);
        model.addAttribute("dept", depts.get(0));

        List<Emp> emps = empService.findEmpsByDeptId(depts.get(0).getId());
        model.addAttribute("emps", emps);


        boolean isManager = ShiroUtils.isManager();
        boolean isSuper = ShiroUtils.isSuperAdmin();
        if(isManager || isSuper){
            model.addAttribute("showRankAmount", true);
        }else{
            model.addAttribute("showRankAmount", false);
        }

        List<Integer> months = new ArrayList<>();
        for(int i = 1; i <= 12; i++){
            months.add(i);
        }
        model.addAttribute("months", months);

        return prefix + "/search_emp";
    }

    /*@RequestMapping("/orderList")
    @ResponseBody
    public PageVO<Order> orderList(@RequestBody Map<String, Object> params){
        Page<Order> page = orderService.queryOrderPage(params);
        PageVO<Order> pageVO = new PageVO<>();
        pageVO.setTotal(page.getTotal());
        pageVO.setRows(page.getRecords());
        return pageVO;
    }*/

    @GetMapping("/gotoAdd/{orderId}")
	public String gotoAdd(@PathVariable("orderId") Long orderId, Model model){
        Effort effort = new Effort();
        Date workDt = new Date();
        effort.setOrderId(orderId);
        effort.setWorkDt(workDt);

        String orderNo = orderService.selectById(orderId).getOrderNo();
        effort.setOrderNo(orderNo);

        addOtherInfo(model, effort);
	    return prefix + "/search";
	}

	private void addOtherInfo(Model model, Effort effort){
        List<Dept> depts = deptService.findAllProdGroupTwoDepts();
        model.addAttribute("depts", depts);
        model.addAttribute("effort", effort);

        List<Effort> efforts = null;
        // 默认加载第一组的员工
        if(depts == null || depts.isEmpty()){
            efforts = new ArrayList<>();
        }else{
            Long deptId = effort.getDeptId() == null ? depts.get(0).getId() : effort.getDeptId();
            effort.setDeptId(deptId);
            efforts = effortService.findEffortsByDeptOrderAndDt(effort.getDeptId(), effort.getOrderId(), effort.getWorkDt());
        }
        model.addAttribute("efforts", efforts);
    }

	@PostMapping("/reload")
    public String reload(Effort effort, Model model){
        addOtherInfo(model, effort);
        return prefix + "/search";
    }

    @Log("保存工时")
    @PostMapping("/save")
    @ResponseBody
    public ResMsg save(Long orderId, Date workDt, Long deptId, String efforts){
        // efforts 的格式为：  efforts[0][0].empId=e1;efforts[0][0].id=;efforts[0][0].workHour=1
        Map<String, Effort> map = new HashMap<>();

        Effort effort = null;
        String[] effortArr = efforts.split(";");
        for(String eff : effortArr){
            String[] keyVal = eff.split("=");
            String[] indAttr = keyVal[0].split("\\.");

            String val = keyVal.length == 1 ? "" : keyVal[1]; // 等号后面没有值
            if(map.containsKey(indAttr[0])){
                effort = map.get(indAttr[0]);
            }else{
                effort = new Effort();
                map.put(indAttr[0], effort);
            }
            if("id".equals(indAttr[1])){
                if(StringUtils.isNotBlank(val)){
                    effort.setId(Long.parseLong(val));
                }
            }else if("empId".equals(indAttr[1])){
                effort.setEmpId(Long.parseLong(val));
            }else if("beginTime".equals(indAttr[1])){
                effort.setBeginTime(StringUtils.isEmpty(val)? null : val);
            }else if("endTime".equals(indAttr[1])){
                effort.setEndTime(StringUtils.isEmpty(val)? null : val);
            }else if("reduce".equals(indAttr[1])){
                effort.setReduce(StringUtils.isEmpty(val)? new BigDecimal(0) : new BigDecimal(val));
            }else if("workHour".equals(indAttr[1])){
                effort.setWorkHour(StringUtils.isEmpty(val)? null : new BigDecimal(val));
            }
        }

        List<Effort> effortList = new ArrayList<>();
        for(String key : map.keySet()){
            effort = map.get(key);
            if(effort.getWorkHour() == null){
                continue;
            }
            effort.setWorkDt(workDt);
            Calendar cal = Calendar.getInstance();
            cal.setTime(workDt);
            effort.setMonth(cal.get(Calendar.MONTH)+1);
            effort.setOrderId(orderId);
            effort.setDeptId(deptId);
            effortList.add(effort);
        }
        if(effortList.isEmpty()){
            return ResMsg.error("没有记录可以保存。请确保记录完整。");
        }
        effortService.insertOrUpdateBatch(effortList);
        effortList = effortService.findEffortsByDeptOrderAndDt(deptId, orderId, workDt);
        Map<String, Long> ids = new HashMap<>();
        for(Effort eff : effortList){
            ids.put("emp" + eff.getEmpId(), eff.getId());
        }

        return ResMsg.ok(ids);
    }

	@GetMapping("/gotoEdit/{id}")
	String gotoEdit(@PathVariable("id") Long id, Model model){
        Effort effort = effortService.selectById(id);
		model.addAttribute("effort", effort);
        model.addAttribute("isEdit", true);
	    return prefix + "/add";
	}


    /**
     * 设置订单在二部已完成生产
     * @param orderId
     * @return
     */
	@PostMapping("/updateToFinish/{orderId}")
    @ResponseBody
    public ResMsg updateToFinish(@PathVariable("orderId") Long orderId){
        orderService.updateToFinish(orderId);
        return ResMsg.ok();
    }

    /**
     * 获得这段时间内属于这个部门的员工，此方法现在仅用于获得二部下面的每个分组的员工
     * @param year
     * @param month
     * @param deptId
     * @return
     */
    @GetMapping("/getEmpsByDeptId")
    @ResponseBody
    public ResMsg getEmpsByDeptId(@RequestParam("year") int year,
                                  @RequestParam("month") int month,
                                  @RequestParam("deptId") long deptId){
        return ResMsg.ok(effortService.getEmpsByDeptId(year, month, deptId));
    }

    @GetMapping("/getEmpRankAmount")
    @ResponseBody
    public ResMsg<RankAmount> getEmpRankAmount(@RequestParam("year") int year,
                                               @RequestParam("month") int month,
                                               @RequestParam("empId") long empId){
        return ResMsg.ok(effortService.getEmpRankAmount(year, month, empId));
    }

    /**
     * 得到某个二部员工工作效率的原始数据
     * @param year
     * @param month
     * @param empId
     * @return
     */
    @GetMapping("/effortOriginalData")
    @ResponseBody
    public PageVO<OrderEffortDTO> effortOriginalData(@RequestParam("year") int year,
                                            @RequestParam("month") int month,
                                            @RequestParam("empId") long empId){
        PageVO<OrderEffortDTO> pageVO = new PageVO<>();
        if(empId == -1L){
            return pageVO;
        }

        List<OrderEffortDTO> list = effortService.getEmpWorkOrderInfo(year, month, empId);

        pageVO.setTotal(list.size());
        pageVO.setRows(list);
        return pageVO;
    }

}

